import React, { useEffect, useState } from 'react';
import { PlusOutlined, CopyOutlined } from '@ant-design/icons';
import { Form, Input, Button, message } from 'antd';
import QuestionWrapper from '../components/QuestionEditor/QuestionWrapper';
import { createQuestion } from '../utils/questionTemplate';
import { createSurvey, publishSurvey } from '../services/survey';
import { getEmailFromToken } from '../utils/getemailfromtoken';

const createid = getEmailFromToken();

const CreateSurveyPage = ({
  title,
  setTitle,
  description,
  setDescription,
  questions,
  setQuestions,
}) => {
  const [form] = Form.useForm();

  // 发布后问卷链接状态
  const [publishedLink, setPublishedLink] = useState('');

  // 表单内容随title/description变化而变化
  useEffect(() => {
    form.setFieldsValue({
      title,
      description,
    });
  }, [title, description, form]);

  // 监听表单输入，更新父组件状态
  const onValuesChange = (changedValues) => {
    if (changedValues.title !== undefined) {
      setTitle(changedValues.title);
    }
    if (changedValues.description !== undefined) {
      setDescription(changedValues.description);
    }
  };

  // 发布问卷函数，发布成功后清空父组件内容，并显示链接
  const handlePublish = async () => {
    try {
      await form.validateFields();
      const values = form.getFieldsValue();

      const res = await createSurvey({
        title: values.title,
        description: values.description || '',
        creatorId: createid,
        questions: questions.map(q => ({
          ...q,
          id: undefined,
        })),
      });

      const link = await publishSurvey(res.data.data.id);

      setPublishedLink(link); // 显示发布链接

      // 清空父组件状态，重置内容
      setTitle('');
      setDescription('');
      setQuestions([]);

      // 重置表单内容
      form.resetFields();

      message.success('问卷发布成功！');
    } catch (error) {
      message.error(error.message || '发布过程中出现错误');
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: 24 }}>
      <Form
        form={form}
        layout="vertical"
        onValuesChange={onValuesChange}
      >
        {/* 问卷标题 */}
        <Form.Item
          label="问卷标题"
          name="title"
          rules={[{ required: true, message: '请输入问卷标题' }]}
        >
          <Input placeholder="例：用户满意度调查" />
        </Form.Item>

        {/* 问卷描述 */}
        <Form.Item
          label="问卷描述"
          name="description"
          extra="选填，用于说明问卷目的或填写注意事项"
        >
          <Input.TextArea
            rows={4}
            placeholder="例：本问卷用于收集用户对我们产品的使用反馈"
          />
        </Form.Item>

        {/* 题目列表 */}
        <div style={{ margin: '24px 0' }}>
          {questions.map((question, index) => (
            <QuestionWrapper
              key={question.id}
              question={question}
              index={index}
              updateQuestion={(newQuestion) => {
                const updated = [...questions];
                updated[index] = newQuestion;
                setQuestions(updated);
              }}
              deleteQuestion={() => {
                setQuestions(questions.filter((_, i) => i !== index));
                message.info('题目已删除');
              }}
            />
          ))}
        </div>

        {/* 添加题目按钮 */}
        <Button
          type="dashed"
          onClick={() => setQuestions([...questions, createQuestion('single')])}
          block
          icon={<PlusOutlined />}
          style={{ marginBottom: 24 }}
        >
          添加新题目
        </Button>

        {/* 发布按钮 */}
        <Button
          type="primary"
          onClick={handlePublish}
          size="large"
          block
        >
          立即发布
        </Button>

        {/* 发布成功显示链接 */}
        {publishedLink && (
          <div style={{
            marginTop: 24,
            padding: 16,
            backgroundColor: '#f6ffed',
            border: '1px solid #b7eb8f',
            borderRadius: 4,
          }}>
            <p style={{ marginBottom: 8 }}>🎉 发布成功！问卷链接：</p>
            <div style={{ display: 'flex', gap: 8 }}>
              <Input
                value={publishedLink}
                readOnly
                style={{ flex: 1 }}
              />
              <Button
                icon={<CopyOutlined />}
                onClick={() => {
                  navigator.clipboard.writeText(publishedLink);
                  message.success('链接已复制到剪贴板');
                }}
              >
                复制
              </Button>
            </div>
            <p style={{
              marginTop: 8,
              color: '#666',
              fontSize: 12,
            }}>
              提示：此链接可分享给填写者
            </p>
          </div>
        )}
      </Form>
    </div>
  );
};

export default CreateSurveyPage;
